package com.yu1996.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yu1996.common.constant.ProductConstant;
import com.yu1996.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.yu1996.gulimall.product.dao.AttrGroupDao;
import com.yu1996.gulimall.product.dao.CategoryDao;
import com.yu1996.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.yu1996.gulimall.product.entity.AttrGroupEntity;
import com.yu1996.gulimall.product.entity.CategoryEntity;
import com.yu1996.gulimall.product.service.CategoryService;
import com.yu1996.gulimall.product.vo.AttrGroupRelationVo;
import com.yu1996.gulimall.product.vo.AttrRespVo;
import com.yu1996.gulimall.product.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu1996.common.utils.PageUtils;
import com.yu1996.common.utils.Query;

import com.yu1996.gulimall.product.dao.AttrDao;
import com.yu1996.gulimall.product.entity.AttrEntity;
import com.yu1996.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存基本属性和属性分组
     *
     * @param attr
     */
    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        //首先保存基本属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode().equals(attr.getAttrType()) && attr.getAttrGroupId() != null) {
            //然后再保存基本属性和属性分组的关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            //获得刚刚新增的属性ID
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    /**
     * 根据key模糊查询分页显示列表
     *
     * @param params
     * @param type
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", type.equals("base") ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SOLE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.like("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),
                queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        // 查到属性后还要结合分类名字、分组名字(分类->属性->分组) 封装为AttrRespVo对象
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            //先将相同的属性映射到AttrRespVo中
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
//            log.error("attrEntity:"+attrEntity+"----------attrRespVo:"+attrRespVo);

            if ("base".equalsIgnoreCase(type)) {
                //根据属性、属性分组关系表查询属性分组名
                AttrAttrgroupRelationEntity attrId = relationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId()));
                if (attrId != null && attrId.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntities = attrGroupDao.selectById(attrId.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntities.getAttrGroupName());
                }
            }
            //再将分类的名称封装到vo中
            CategoryEntity category = categoryDao.selectById(attrRespVo.getCatelogId());
            if (!StringUtils.isEmpty(category.getName())) {
                attrRespVo.setCatelogName(category.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    /**
     * 根据id查询AttrRespVo
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        //首先封装基本属性
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        //封装基本属性分组信息
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode().equals(attrRespVo.getAttrType())) {
            AttrAttrgroupRelationEntity attrAttrgroupRelation = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attrAttrgroupRelation != null && attrAttrgroupRelation.getAttrGroupId() != null) {
                attrRespVo.setAttrGroupId(attrAttrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //封装属性分类的信息
        CategoryEntity category = categoryDao.selectById(attrRespVo.getCatelogId());
        if (category != null) {
            Long[] catelogPath = categoryService.findCatelogPath(category.getCatId());
            attrRespVo.setCatelogPath(catelogPath);
            attrRespVo.setCatelogName(category.getName());
        }
        return attrRespVo;
    }

    /**
     * 更新AttrRespVo
     */
    @Override
    @Transactional
    public void updateAttr(AttrRespVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //首先更新属性基本信息
        this.updateById(attrEntity);

        //更新属性的关联信息
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode().equals(attr.getAttrType()) && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            //判断关联表中有没有该属性的分组   如果有就更新  没有就新增
            Integer attr_id = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (attr_id > 0) {
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }
        }

    }

    /**
     * 根据分组id找到相关联的属性
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        //先在属性关联表中查到分组ID所有对应的属性集合
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        //将所有的属性id抽取出来
        List<Long> attrIDs = entities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        if (attrIDs == null || attrIDs.size() == 0) {
            return null;
        }
        //根据id集合查询所有的属性
        Collection<AttrEntity> attrEntities = this.listByIds(attrIDs);

        return (List<AttrEntity>) attrEntities;
    }

    /**
     * 根据属性分组vo删除关联信息
     *
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        //将vo数组对象转成relation关联集合
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((relationVo) -> {
            BeanUtils.copyProperties(relationVo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        //一次性删除，不发送多条语句
        relationDao.deleteBatchRelation(collect);
    }

    /**
     * Description: 获得当前分组中所有没有被关联的属性
     * Date: 2021/9/6
     * Author: yu
     */
    @Override
    public PageUtils getNoRelationAttr(Long attrGroupId, Map<String, Object> params) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)、当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2)、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3)、从当前分类的所有属性中移除这些属性；
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }


}